<!-- roleDetailPage.vue -->
<template>
  <div class="role-detail-container">
    <el-card class="role-basic-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>    

      <el-form ref="roleForm" :model="roleData" :rules="roleRules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleData.name" placeholder="请输入角色名称" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="角色备注" prop="remark">
          <el-input v-model="roleData.remark" type="textarea" placeholder="请输入角色备注" :disabled="isViewMode" :rows="3" />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="role-permission-card">
      <template #header>
        <div class="card-header">
          <span>权限设置</span>
        </div>
      </template>

      <menu-tree-widget ref="permissionTree" :menu-tree="menuTree" :initPermission=role?.permission
        @permission-change="handlePermissionChange" :disabled="isViewMode" />

    </el-card>

    <div class="form-actions" v-if="!isViewMode">
      <el-button type="primary" @click="saveRole">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction'
import { Engine } from '../../public/engine/engine'
import MenuTreeWidget from './menuTreeWidget.vue'
import { PermissionInfo } from '../../public/engine/menus/permissionInfo'
import { MenuData } from '../../public/engine/menus/menuData'
import { Role } from '../../public/engine/enterpriseMgt/role'
import TabUtil from '@/plugins/tab'
import EventBus from '../../public/engine/ipc/eventBus'

export default {
  name: 'roleDetail',

  components: {
    MenuTreeWidget
  },

  data() {
    return {
      roleData: {
        id: undefined,
        name: '',
        remark: ''
      },

      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },

      menuTree: [],
      selectedPermissions: [],
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      orgId: Engine.profile.org.orgId,
      loading: false,
      role: null,
      // 返回数据
      retValue: null,
    }
  },

  computed: {
    isViewMode() {
      // Determine if we're in view mode based on route parameters
      return this.$route.query.mode === 'view'
    },

    isEditMode() {
      // Determine if we're editing an existing role
      return true;
    }
  },

  async mounted() {
    // Get menu tree from permission manager
    this.menuTree = Engine.profile?.permissionMgr?.getMenuShowableMenuTree(false, true) ?? []

    // Load role data if editing
    this.role = Role.empty();
    await this.loadRoleData()

  },

  beforeUnmount() {
    if (this.retValue) {
      EventBus.emit('roleDataUpdated', null);
      this.retValue = null;
    }
  },

  deactivated() {
    if (this.retValue) {
      EventBus.emit('roleDataUpdated', null)
      this.retValue = null;
    }
  },


  methods: {
    async loadRoleData() {
      try {
        this.loading = true
        const id = this.$route.params.id || this.$route.query.id;

        console.log('loadRoleData id', id)

        if (!id) return

        // Get role data from API
        const roleInfo = await this.enterpriseMgtUiAction.getRoleDetailInfo(id)



        if (roleInfo) {
          this.role = roleInfo;
          this.roleData = {
            id: roleInfo.id,
            name: roleInfo.name,
            remark: roleInfo.remark
          }

          // Set selected permissions from role data
          // this.selectedPermissions = res.data.menuIds || []
        }
      } catch (error) {
        console.error('加载角色数据失败', error)
        ElMessage.error('加载角色数据失败')
      } finally {
        this.loading = false
      }
    },

    handlePermissionChange(permissions) {
      console.log('handlePermissionChange', permissions)
      this.selectedPermissions = permissions
    },

    closeTest() {
      TabUtil.closePage(); // 关闭tab 页面
    },
    async saveRole() {
      try {
        // Validate form
        await this.$refs.roleForm.validate()

        this.loading = true

        // Prepare role data

        // 复制角色信息
        this.role.name = this.roleData.name
        this.role.remark = this.roleData.remark

        // 拷贝获取到的权限
        let permissionInfo = new PermissionInfo()
        this.selectedPermissions.forEach(permission => {
          permissionInfo.menuTree.push(new MenuData(permission))
        })

        this.role.permission = permissionInfo
        const res = this.enterpriseMgtUiAction.updateOrCreateRoleData(this.role);

        if (res) {
          this.retValue = this.role;
          if (this.role.id) {
            ElMessage.success('角色更新成功');
          
          } else {
              setTimeout(() => {             
              TabUtil.closePage();
            }, 1000); // 1000ms = 1 second
          }

        }
      } catch (error) {
        console.error('保存角色失败', error)
        ElMessage.error('保存角色失败')
      } finally {
        this.loading = false
      }
    },

    cancel() {
      this.$router.back()
    }
  }
}
</script>

<style scoped>
.role-detail-container {
  padding: 20px;
  max-width: 1200px;
}

.role-basic-card,
.role-permission-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.form-actions {
  padding: 20px 0;
}

.form-actions .el-button {
  margin: 0 10px;
}

.role-permission-card :deep(.el-card__body) {
  padding: 0;
}
</style>